# _*_ coding:utf-8 _*_
from django import template

from auser.models import User
from movie.models import Stamp
from post.models import CommentPraise

register = template.Library()


# 如果已建立数据关系，返回其赞表数据行
def get_praise(comment, uid):
	praise = comment.commentpraise_set.filter(user_id=uid)
	return praise[0] if praise else None


class PcommentController(object):
	def __init__(self, comment):
		self.comment = comment
		self.pcomment = self.get_parent()

	def get_parent(self):
		try:
			if self.comment.parent_comment_id is not None:
				pcomment = self.comment.parent_comment
				return pcomment
		except Exception:
			return ""

	def get_parent_content(self):
		try:
			return self.pcomment.content.encode('utf8')
		except:
			return ""

	def get_parent_author(self):
		try:
			return self.pcomment.user_username.encode('utf8')
		except:
			return ""

	def get_parent_timestamp(self):
		try:
			return self.pcomment.timestamp.strftime('%Y-%m-%d')
		except:
			return ""


# 验证当前用户是否有点赞表或已点赞
def get_status(comment, uid):
	praise = comment.commentpraise_set.filter(user_id=uid)
	if praise and praise[0].status == True:
		return True
	return False


# FAQ: 评论树还是有问题
"""
def recursive_build_tree(html_ele, comment_tree):
	for p_comment, c_comment in comment_tree.items():
		row = '''
		<div class="comment">
			  <a class="avatar">
			  <img src="{avatar}"></a>
			  <div class="content"> 
		      <a class="author">{name}</a> 
		      <div class="metadata"><span class="date">{timestamp}</span></div> 
		      <div class="text">{content}</div> 
		      <div class="actions">
		      <a class="reply to-reply">Reply</a>
		      <span class="comment=id" style="display: none;">{id}</span>
		      </div></div>
		      '''.format(avatar=p_comment.user.avatar,
		                 id=p_comment.id,
		                 name=p_comment.user_username.encode('utf8'),
		                 content=p_comment.content.encode('utf8'),
		                 timestamp=p_comment.timestamp.strftime('%Y-%m-%d').encode('utf8'))
		html_ele += row
		if c_comment:
			html_ele += '<div class="comments">'
			html_ele = recursive_build_tree(html_ele, comment_tree[p_comment])
	return html_ele + '</div>'
"""


# REW: 字典数据结构构造评论树
@register.simple_tag
def build_comment_tree(comment_tree, uid):
	html_ele = """
				<div class="ui threaded comments">
				<h3 class="ui dividing header">Comments</h3>
				<a class ="ui dividing header" id="writeComment">我要写短评</a>
	"""
	# 根评论
	for p_comment, c_comment in comment_tree.items():
		row = '''
		<div class="comment" id="{id}">
			  <a class="avatar">
			  <img src="{avatar}"></a>
			  <div class="content"> 
		      <a class="author">{name}</a> 
		      <div class="metadata"><span class="date">{timestamp}</span></div> 
		      <div class="parent_comment {pid}">
		      <a class="author">{pname}: <span>{pcontent}</span></a>
		      <div class="metadata"><span class="date">{ptimestamp}</span></div>  
		      </div>
		      <div class="text">{content}</div> 
		      <div class="actions">
		      <a class="reply to-reply">Reply</a>
		      <a class="like"  data-status="{status}" data-like="{lid}" comment-id="{id}"><img src="/static/movie/images/like-off.png" />
		      <span class="zan">{score}</span></a>
		      <span class="comment-id" style="display: none;">{id}</span>
		      </div></div></div>
		      '''.format(avatar=p_comment.user.avatar,
		                 lid=get_praise(p_comment, uid).id if get_status(p_comment, uid) else '',
		                 id=p_comment.id,
		                 status="1" if get_status(p_comment, uid) else "0",
		                 name=p_comment.user_username.encode('utf8'),
		                 pid="" if PcommentController(p_comment).get_parent() else "is",
		                 pcontent=PcommentController(p_comment).get_parent_content(),
		                 pname=PcommentController(p_comment).get_parent_author(),
		                 ptimestamp=PcommentController(p_comment).get_parent_timestamp(),
		                 content=p_comment.content.encode('utf8'),
		                 score=p_comment.score,
		                 timestamp=p_comment.timestamp.strftime('%Y-%m-%d'))
		html_ele += row  # 迭代根评论
	# if c_comment:
	# 	# print('0-0'+html_ele[0:3])
	# 	# html_ele = html_ele[:-6]
	# 	html_ele += '<div class="comments">'
	# 	html_ele = recursive_build_tree(html_ele, comment_tree[p_comment])
	# 	html_ele += "</div>"

	return html_ele + "</div>"


@register.filter
def detect_rate(value):
	value = value.rate if value.rate else None
	return value


@register.filter
def visit_stamp(user, movie_id):
	assert isinstance(user, User)
	stamp = Stamp.objects.filter(user_id=user.id, movie_id=movie_id)
	return stamp[0] if stamp else None
